package com.lagou.task19;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerStringTest {
    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket s = null;
//        BufferedReader br = null;
//        PrintStream ps = null;
        try {
//        1创建ServerSocket类型的对象并提供端口号
            ss = new ServerSocket(8888);
//        2等待客户端的连接请求，调用accept方法
            System.out.println("等待客户端的连接请求");
            while (true){
                s = ss.accept();
                ServerThread st1 = new ServerThread(s);
                st1.start();
            }
            //当没有客户端连接时阻塞在此处
//            s = ss.accept();
//            System.out.println("客户端连接成功");
////        3使用输入输出流进行通信
//            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
//            ps = new PrintStream(s.getOutputStream());
//            while (true) {
//                String s1 = br.readLine();
//                System.out.println("客户端发来的内容是： " + s1);
//                //回复客户端收到的内容I received
//                ps.println("I received");
//                if ("bye".equalsIgnoreCase(s1)){
//                    System.out.println("聊天结束，关闭服务端");
//                    break;
//                }
//            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
////            4关闭socket并释放有关资源
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//            if (br != null) {
//                try {
//                    br.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
        }


    }
}
